/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package molehillempirecalculator.functions;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import molehillempirecalculator.utils.Item;

/**
 * Class Functions.
 * @author Praiet
 */
public class Functions {

    public static Logger log = Logger.getLogger(Functions.class.getName());
    public static String filePath = "src/molehillempirecalculator/resources/pricelist.txt";
    public static List<Item> itemList = new ArrayList<Item>();
    static float sum = 0f;
    public static String[] header = {"id","Nombre","Precio en tienda","Campos Req.","Producción","Precio de mercado"};
    public static Object[][] data = null;

    public static void loadItemList(String path) {

        BufferedReader br = null;
        try {
            File f = new File(path);
            if (f.exists()) {
                log.log(Level.INFO, "File created.");
            } else {
                f.createNewFile();
                log.log(Level.INFO, "File doesn't exist, but created now.");
                log.log(Level.INFO, "File created at: " + f.getAbsolutePath());
            }
            br = new BufferedReader(new FileReader(path));

            String line = null;
            String[] el = null;
            int i=0;
            while ((line = br.readLine()) != null) {
                if (line.startsWith("#")) {
                    itemList.add(new Item(i,line));
                    if (log.isLoggable(Level.INFO)) {
                        log.log(Level.INFO, "Loaded: " + line + " as comment!");
                    }
                    i++;
                    continue;
                }
                el = line.split(",");
                itemList.add(new Item(i,el[0], Float.parseFloat(el[1]),
                        Integer.parseInt(el[2]), Integer.parseInt(el[3]),
                        Float.parseFloat(el[4])));
                if (log.isLoggable(Level.INFO)) {
                    log.log(Level.INFO, "Loaded: " + line);
                }
                i++;
            }
        } catch (FileNotFoundException ex) {
            log.log(Level.SEVERE, null, ex);
        } catch (IOException ioe) {
            log.log(Level.SEVERE, null, ioe);
        } finally {
            try {
                br.close();
            } catch (IOException ex) {
                log.log(Level.SEVERE, null, ex);
            }
        }

        data = new Object[Functions.itemList.size()][Functions.header.length];

        for (int i = 0; i < Functions.itemList.size(); i++) {
            if (!Functions.itemList.get(i).isComment()) {
                data[i][0] = Functions.itemList.get(i).getItemId();
                data[i][1] = Functions.itemList.get(i).getItemName();
                data[i][2] = Functions.itemList.get(i).getItemShopPrice();
                data[i][3] = Functions.itemList.get(i).getItemRequiredFields();
                data[i][4] = Functions.itemList.get(i).getItemProduction();
                data[i][5] = Functions.itemList.get(i).getItemMarketPrice();
            }
        }
    }

    public static void updateItemList(String path) {
        //TODO: write the file from the itemList. Same as loadItemList, but with a BufferedWriter instead of a BufferedReader.
        BufferedWriter bw = null;
        try {
            File f = new File(path);
            if (f.exists()) {
                log.log(Level.INFO, "File created.");
            } else {
                f.createNewFile();
                log.log(Level.INFO, "File doesn't exist, but created now.");
                log.log(Level.INFO, "File created at: " + f.getAbsolutePath());
            }
            bw = new BufferedWriter(new FileWriter(path));

            for (int i = 0; i < itemList.size(); i++) {
                if (itemList.get(i).isComment()) {
                    bw.write(itemList.get(i).getItemName());
                } else {
                    bw.write(itemList.get(i).getItemName());
                    bw.write(",");
                    bw.write(Float.toString(itemList.get(i).getItemShopPrice()));
                    bw.write(",");
                    bw.write(Integer.toString(itemList.get(i).getItemRequiredFields()));
                    bw.write(",");
                    bw.write(Integer.toString(itemList.get(i).getItemProduction()));
                    bw.write(",");
                    bw.write(Float.toString(itemList.get(i).getItemMarketPrice()));
                }
                if (i < itemList.size() - 1) {
                    bw.write("\n");
                }
                if (log.isLoggable(Level.INFO)) {
                    log.log(Level.INFO, "Loaded " + itemList.get(i).getItemName());
                }
            }

        } catch (FileNotFoundException ex) {
            log.log(Level.SEVERE, null, ex);
        } catch (IOException ioe) {
            log.log(Level.SEVERE, null, ioe);
        } finally {
            try {
                bw.close();
            } catch (IOException ex) {
                log.log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * Function that return the number of lines for the given String
     * @param s
     * @return
     */
    public static String numberOfLines(String s) {
        String[] aux = s.split("\n");

        for (String au : aux) {
            String[] au2 = au.split(" ");
            int itm;
            if (au2.length == 2) {
                if ((itm = getItemListIndex(au2[1])) != -1) {
                    itemList.get(itm).setItemQty(Integer.parseInt(au2[0].substring(0, au2[0].length() - 1)));
                }
            } else if (au2.length == 3) {
                if ((itm = getItemListIndex(au2[1] + " " + au2[2])) != -1) {
                    itemList.get(itm).setItemQty(Integer.parseInt(au2[0].substring(0, au2[0].length() - 1)));
                } else if (au2[2].equalsIgnoreCase("TG")) {
                    String[] number = au2[1].split(",");
                    sum = Float.parseFloat(number[0].replace(".", "") + "." + number[1]);
                }
            }
        }
        String ret = spaces("Nombre") + "\t" + spaces("Cantidad") + "\n";
        ret += spaces("------") + "\t" + spaces("--------") + "\n";
        for (Item it : itemList) {
            if (!it.isComment() && it.getItemQty() != 0) {
                ret += spaces(it.getItemName()) + "\t" + spaces("" + it.getItemQty()) + "\n";
            }
        }
        ret += "Total Sum: " + sum + " TG";
        return ret;
    }

    /**
     * It flushes the itemList.
     */
    public static void flushItemList() {
        for (Item it : itemList) {
            if (!it.isComment()) {
                it.setItemQty(0);
            }
        }
    }

    /**
     * Tries to look for the index of a specified itemName.
     * @param itemName
     * @return - If index >= 0, the index in the list.<br>
     * If negative, it doesn't exist in the list.
     */
    public static int getItemListIndex(String itemName) {
        int ret = -1;
        for (int i = 0; i < itemList.size(); i++) {
            if (itemList.get(i).getItemName().equalsIgnoreCase(itemName)
                    && !itemList.get(i).isComment()) {
                ret = i;
                break;
            }
        }
        return ret;
    }

    /**
     * Adds the spaces in the presentation as defaultSpace=25.
     * @param name
     * @return
     */
    public static String spaces(String name) {
        String ret = name;
        int defaultSpace = 25;
        if (defaultSpace > name.length()) {
            int i = defaultSpace - name.length();
            for (int j = 0; j < i; j++) {
                ret += " ";
            }
        }
        return ret;
    }

    public static void loadTable(JTable jt) {
        


    }
}
